import { showMessage } from '@/components/antd-comp/message'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { WorkflowRunningStatus } from '@/components/workflow/types'
import CreateSkills from '@/pages/workflow/flowCreate'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { useWorkFlowStore } from '@/store/workflowStore'
// import { ExclamationCircleFilled, LeftOutlined } from '@ant-design/icons'
import { LeftOutlined } from '@ant-design/icons'
import { Button, Modal } from 'antd'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { workflowPublishApi } from '../API'
import { useCheckLinkStatus } from '../hooks/use-chek-link'
import { useAutoSave } from '../hooks/use-save'
import { checkArrayMessFun, checkNodeValidity, removeUnreachableInfo } from '../utils'
import './index.less'

const { confirm } = Modal
export default function Header({ flow, onRunTest }) {
  const navigate = useNavigate()

  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()

  const {
    disabledPublish,
    updateTime,
    runTime,
    publishTime,
    flowInstance,
    flowVariables,
    setPublishTime,
    setVerifying,
    updateRunType,
    setFlowVariables,
    coverFlowVariables,
    clearRunInfo,
    updateSingleRunningInfo
  } = useWorkFlowStore()

  const { autoSave } = useAutoSave()
  const { checkLinkStatus } = useCheckLinkStatus()

  // 试运行
  const handleTest = () => {
    console.log('试运行')
    updateRunType('all')
    onRunTest(prev => !prev) // 切换面板状态
  }
  // 保存版本
  const handleSaveEvent = async () => {
    await autoSave(flow.id, true)
  }

  useEffect(() => {
    loadTypeList()
  }, [])

  /* 编辑 */
  const { loadDictOptions } = useDictStore()
  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then(res => {
      if (res) {
        const list = [...res]
        setSearchListDialog(list)
      }
    })
  }
  const [open, setOpen] = useState(false)
  const [info, setInfo] = useState({})
  const [SearchListDialog, setSearchListDialog] = useState([])

  const processNode = (node, nodeId, nodeTitle) => {
    return new Promise(resolve => {
      const nodeType = node.node_type
      if (!checkNodeValidity(node, nodeType)) {
        // setFlowVariables(nodeId, nodeTitle, { ...node })

        updateSingleRunningInfo(nodeId, WorkflowRunningStatus.Invalid)
        resolve(false)
      } else {
        // setFlowVariables(nodeId, nodeTitle, { ...node })
      }
      resolve(true)
    })
  }
  const verifyAndProcessNodes = async () => {
    clearRunInfo()

    if (!checkLinkStatus()) {
      return false
    }

    setVerifying(true)

    // 清除不存在节点的连线
    const currentNodes = flowInstance.getNodes();
    const currentEdges = flowInstance.getEdges();
    const validEdges = currentEdges.filter(edge => {
      const sourceExists = currentNodes.some(node => node.id === edge.source);
      const targetExists = currentNodes.some(node => node.id === edge.target);
      return sourceExists && targetExists;
    });
    
    if (validEdges.length !== currentEdges.length) {
      flowInstance.setEdges(validEdges);
    }

    const currentFlowVariables = removeUnreachableInfo(
      null,
      currentNodes,
      validEdges,
      flowVariables
    )
    coverFlowVariables(currentFlowVariables)
    const nodePromises = Object.values(currentFlowVariables).map((item: any) => processNode(item, item.id, item.title))

    const results = await Promise.all(nodePromises)
    const status = results.every(success => success)

    if (!status) {
      checkArrayMessFun('error')
    }
    return status
  }

  const checkBeforeRun = async () => {
    const status = await verifyAndProcessNodes()
    if (status) {
      handleTest()
    } else {
      /* 2个提示信息 */
      // checkArrayMessFun('error')
    }
  }
  const submitPublish = async () => {
    try {
      setPublishLoading(true)
      // await handleSaveEvent() // 发布前不自动保存，否则会将未自动保存的内容进行保存
      const res: any = await workflowPublishApi(flow.id)
      if (res?.publish_time) {
        setPublishTime(res.publish_time.replace('T', ' '))
      }
      showMessage({
        content: '发布成功',
        type: 'success'
      })
    } catch (error) {
      console.log('error', error)
    } finally {
      setPublishLoading(false)
    }
  }

  const [publishLoading, setPublishLoading] = useState(false)
  const originalHandlePublishVersion = async () => {
    if (!hasFuncPermission([Func.workflow.publish])) {
      return
    }
    if (publishLoading) {
      return
    }

    if (disabledPublish) {
      showMessage({
        content: '必须试运行成功后才能发布',
        type: 'warning'
      })
      return
    }

    const status = await verifyAndProcessNodes()
    if (!status) {
      // checkArrayMessFun('error')
      return
    }

    console.log('发布当前版本')
    if (!runTime || dayjs(runTime).valueOf() < dayjs(updateTime).valueOf()) {
      showMessage({
        content: '必须试运行成功后才能发布',
        type: 'warning'
      })
      // confirm({
      //   title: '提示',
      //   icon: <ExclamationCircleFilled />,
      //   content: '发布前未进行试运行,建议确保工作流程正常运行后再发布?',
      //   okText: '坚持发布',
      //   okType: 'danger',
      //   cancelText: '取消',
      //   autoFocusButton: null,
      //   centered: true,
      //   destroyOnClose: true,
      //   onCancel() {},
      //   onOk() {
      //     submitPublish()
      //   }
      // })
    } else {
      submitPublish()
    }
  }
  // const handlePublishVersion = debounce(originalHandlePublishVersion, 500)

  return (
    <div className="workflow-header-container flex items-center justify-between border-b px-4">
      <div className="flex items-center gap-2 py-2">
        <LeftOutlined
          className="cursonCase h-4 w-4"
          onClick={() => {
            autoSave(flow.id, true)
            navigate('/workflow', { replace: true })
          }}
        />
        <div className="mx-[4px] flex flex-col">
          <div className="flex items-center gap-[8px]">
            <span className="text-[16px] font-bold">{flow.name || '工作流'}</span>
            <div>
              <svg
                className="cursonCase"
                onClick={e => {
                  const { name, description, logo, category_code, id } = flow
                  setInfo({ name, desc: description, logo, category_code, id })
                  setOpen(true)
                }}
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M2 14V11L11 2L14 5L5 14H2Z"
                  stroke="#7587A5"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path d="M11 8L8 5" stroke="#7587A5" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M9 14L14 14" stroke="#7587A5" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
          </div>
          {updateTime && (
            <div className="flex gap-[8px]">
              <span className="text-[12px] text-[#7587a5]">
                {updateTime ? `已自动保存 ${dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}
              </span>
              <span className="text-[12px] text-[#7587a5]">
                {publishTime && dayjs(publishTime).valueOf() < dayjs(updateTime).valueOf() ? `有尚未发布的修改` : ''}
              </span>
            </div>
          )}
        </div>
      </div>

      <div className="flex">
        <Button
          className="closeBtnStyles header-right-btn"
          shape="round"
          onClick={checkBeforeRun}
          style={{ color: '#131921' }}
        >
          试运行
        </Button>
        <ThemeBtn
          loading={publishLoading}
          className="header-right-btn"
          style={{ color: '#FFFFFF' }}
          onClick={originalHandlePublishVersion}
        >
          发布
        </ThemeBtn>
        {/* <ThemeBtn className="header-right-btn" style={{ color: '#FFFFFF' }} onClick={handlePublishVersion}>
          发布
        </ThemeBtn> */}
      </div>
      {/* 编辑 */}
      {open ? (
        <CreateSkills
          open={open}
          setOpen={setOpen}
          obj={info}
          dropList={SearchListDialog}
          submitData={() => {
            showMessage({
              content: '修改成功',
              type: 'success'
            })
          }}
        ></CreateSkills>
      ) : null}
    </div>
  )
}
